package com.swapper.json.temp;

import com.swapper.json.io.JsonReader;
import com.swapper.json.io.JsonWriter;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

public class ArrayAdapterFactory {


  public static void main(String[] args) throws IOException {
    String json = "[null,123,1.23,0.564,1e2,2e-2]";
    JsonReader reader = new JsonReader(new StringReader(json));
    ArrayAdapter<Float[], Float> adapter = new ArrayAdapter<>(
      Float.class, new FloatAdapter()
    );

    Float[] read = adapter.read(reader);
    System.out.println(Arrays.toString(read));

  }


  public static class ArrayAdapter<A, C> implements TypeAdapter<A> {
    private final Class<? super C> _componentType;
    private final TypeAdapter<C> _componentAdapter;

    public ArrayAdapter(Class<? super C> componentType, TypeAdapter<C> componentAdapter) {
      _componentType = componentType;
      _componentAdapter = componentAdapter;
    }

    @Override
    public A read(JsonReader reader) throws IOException {
      int token = reader.peek();
      if (token == JsonReader.TOKEN_NULL) {
        reader.nextNull();
        return null;
      }
      ArrayList<C> list = new ArrayList<>();
      reader.beginArray();
      while (reader.hasNext()) {
        list.add(_componentAdapter.read(reader));
      }
      reader.endArray();

      int size = list.size();
      Object array = Array.newInstance(_componentType, size);
      for (int i = 0; i < size; i++) {
        Array.set(array, i, list.get(i));
      }
      return (A) array;
    }

    @Override
    public void write(JsonWriter writer, A value) {

    }
  }
}
